import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../components/status/toast.dart';
import '../../../../controller/network/bridge.dart';
import '../../../../controller/network/network_ctrl.dart';
import '../../../../controller/platform/devices_typing.dart';
import '../../../../controller/platform/platform_ctrl.dart';
import '../../../../pages/Lift/lift_details/ctrl/lift_details_ctrl.dart';
import '../../../../utils/video/video.dart';

class VideoCtrl extends LiftDetailsCtrl {
  final _ldCtrl = Get.find<LiftDetailsCtrl>();

  // 查看网络状态
  final _nc = Get.find<NetworkCtrl>();

  // 用于记录视频流组件加载次数（区分首次加载与路由返回后加载）
  final RxInt _loadingNum = 0.obs;

  // 视频是否连接完成
  final RxBool viodeConnectComplete = false.obs;

  // 是否开启麦克风
  final RxBool microphone = false.obs;

  // 是否开启声音
  final RxBool volume = false.obs;

  // 存储定时器
  Timer cancelTimer = null;

  @override
  void onInit() {
    // 创建网络变化观察
    Bridget.createNetworkCtrl(this);

    // 获取运行的平台
    checkPlatform(PlatformCtrl.runPlatform);

    // 当已获取视频凭证时开启视频流（仅监听一次，用于初始化）
    once(
      _ldCtrl.videoToken,
      (_) {
        // 标记首次视频加载已完成
        _loadingNum.value++;

        // 初始化视频流
        initVideoStream(
          callback: (Map args) {
            Timer(
              Duration(seconds: 2),
              () => viodeConnectComplete.value = args['isComplete'],
            );
            _ldCtrl.viodeConnectfail.value = args['isConnectFail'];
          },
        );
      },
    );

    // 监听组件是否处于激活状态（用于路由返回时调取视频）
    ever(
      _ldCtrl.isActivateStatus,
      (_) {
        // 延时1s执行，防止用户快速返回异步模块未被销毁
        cancelTimer = Timer(Duration(seconds: 1), () {
          if (_ldCtrl.isActivateStatus.value && _loadingNum.value > 0) {
            if (_ldCtrl.videoToken != null) {
              refreshVideoStream();
            }
          } else {
            leaveVideoStream();
          }
        });
      },
    );
  }

  @override
  void onClose() {
    // 移除观察
    Bridget.delNetworkCtrl(this);

    // 取消定时器
    if (cancelTimer != null) cancelTimer.cancel();

    // 关闭视频视频流
    leaveVideoStream();
  }

  @override
  void modify() {
    if (_nc.networkStatus.value && _ldCtrl.isActivateStatus.value) {
      if (_ldCtrl.videoToken.value.appKey != null) refreshVideoStream();
    }
  }

  /// 初始化视频流
  /// * [callback] Function|回调函数|必填
  void initVideoStream({@required Function callback}) {
    Video.getInstance(
      sdk: _ldCtrl.videoToken.value.appKey,
      token: _ldCtrl.videoToken.value.accessToken,
      serialNum: _ldCtrl.videoToken.value.cameraSerial,
      code: _ldCtrl.videoToken.value.cameraVerifyCode,
      num: 0,
    ).startRealPlay(callback: callback);
  }

  /// 刷新视频流
  /// * [isRestart] bool|重启|选填
  void refreshVideoStream({bool isRestart = true}) async {
    // 标记视频重新连接
    viodeConnectComplete.value = false;

    // 标记视频未加载失败
    _ldCtrl.viodeConnectfail.value = false;

    // 关闭音量
    checkPlatform(PlatformCtrl.runPlatform);

    // 关闭对讲
    if (microphone.value) microphone.value = false;

    // 开启视频流
    initVideoStream(callback: (Map args) {
      Timer(
        Duration(seconds: 2),
        () => viodeConnectComplete.value = args['isComplete'],
      );
      _ldCtrl.viodeConnectfail.value = args['isConnectFail'];
    });
  }

  /// 开启/关闭麦克风（对讲）
  void changeMicrophone() async {
    bool _result;

    // 确保视频正常开启
    if (viodeConnectComplete.value) {
      if (microphone.value) {
        // 麦克风处于开启状态
        _result = await Video.closeVoiceTalk();
      } else {
        // 麦克风关闭处于状态
        _result = await Video.startVoiceTalk();
      }

      // 修改麦克风按钮呈现状态
      microphone.value = _result;
    } else {
      Toast.toast(title: "视频未开启请稍后");
    }
  }

  /// 音量开关
  void changeVolume() async {
    bool _result;

    if (viodeConnectComplete.value) {
      if (volume.value) {
        // 音量处于开启状态
        _result = await Video.closeVolume();
      } else {
        // 音量处于关闭状态
        _result = await Video.openVolume();
      }

      volume.value = _result;
    } else {
      Toast.toast(title: "视频未开启请稍后");
    }
  }

  /// 校验运行平台（ios端视频音量默认开启）
  /// * [platformInfo] SystemInfo|运行的平台信息|必填
  void checkPlatform(SystemInfo platformInfo) {
    switch (platformInfo) {
      case SystemInfo.android:
        volume.value = false;
        break;
      case SystemInfo.ios:
        volume.value = true;
        break;
      default:
        volume.value = false;
    }
  }

  /// 组件不处于激活状态（即路由跳转，界面销毁）
  void leaveVideoStream() async {
    // 销毁视频流
    bool _r = await Video.releaseRealPlay();

    // 视频销毁结果
    if (_r) {
      // 标记视频重新连接
      viodeConnectComplete.value = false;

      // 标记视频未加载失败
      _ldCtrl.viodeConnectfail.value = false;
    }
  }
}
